<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
   
  <meta name="keywords" content="Java Python" />
   
  <meta name="description" content="From Zero to Hero" />
  
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    Netty-12-handler调用机制 |  朱酱酱的学习博客
  </title>
  <meta name="generator" content="hexo-theme-yilia-plus">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/css/style.css">

  
<script src="/js/pace.min.js"></script>


  

  

<link rel="alternate" href="/atom.xml" title="朱酱酱的学习博客" type="application/atom+xml">
</head>

</html>

<body>
  <div id="app">
    <main class="content">
      <section class="outer">
  <article id="post-Netty/Netty-12-handler调用机制" class="article article-type-post" itemscope
  itemprop="blogPost" data-scroll-reveal>

  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  Netty-12-handler调用机制
</h1>
  

    </header>
    

    
    <div class="article-meta">
      <a href="/2020/11/05/Netty/Netty-12-handler%E8%B0%83%E7%94%A8%E6%9C%BA%E5%88%B6/" class="article-date">
  <time datetime="2020-11-05T05:05:24.000Z" itemprop="datePublished">2020-11-05</time>
</a>
      
      
      
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">2.2k字</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">8分钟</span>
        </span>
    </span>
</div>

      
    </div>
    

    
    
    <div class="tocbot"></div>





    

    <div class="article-entry" itemprop="articleBody">
      


      

      
      <h1 id="Netty-12-handler调用机制"><a href="#Netty-12-handler调用机制" class="headerlink" title="Netty-12-handler调用机制"></a>Netty-12-handler调用机制</h1><h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><ul>
<li>netty的组件设计：Netty的主要组件有<code>Channel、EventLoop、ChannelFuture、ChannelHandler、ChannelPipe</code>等</li>
<li>我们先来复习一下<code>ChannelHandler</code>和<code>ChannelPipeline</code>的关系。示例图如下：我们可以将<code>pipeline</code>理解为一个双向链表，<code>ChannelHandlerContext</code>看作链表中的一个节点，<code>ChannelHandler</code>则为每个节点中保存的一个属性对象。</li>
</ul>
<p><img src="http://zhuuu-bucket.oss-cn-beijing.aliyuncs.com/img/20201022/123220946.png" alt="mark"></p>
<a id="more"></a>



<ul>
<li><strong><code>ChannelHandler</code>充当了处理入站和出站数据的应用程序逻辑的容器。</strong><ul>
<li>例如，实现<code>ChannelInboundHandler</code>接口（或<code>ChannelInboundHandlerAdapter</code>），你就可以接收入站事件和数据，这些数据会被业务逻辑处理。</li>
<li>当<strong>要给客户端发送响应</strong>时，也可以从<code>ChannelInboundHandler</code>冲刷数据。业务逻辑通常写在一个或者多个<code>ChannelInboundHandler</code>中。</li>
</ul>
</li>
<li><strong><code>ChannelPipeline</code>提供了<code>ChannelHandler</code>链的容器。</strong><ul>
<li>如果事件的运动方向是从<strong>客户端到服务端的，那么我们称这些事件为出站的，即客户端发送给服务端的数据会通过<code>pipeline</code>中的一系列<code>ChannelOutboundHandler</code>,被这些<code>Handler</code>处理</strong></li>
<li>反之则称为入站的</li>
</ul>
</li>
</ul>
<p><strong>下面，来看看我们常用的<code>Handler</code>的关系图：<code>Inbound</code>处理入站，<code>Outbound</code>处理出站</strong></p>
<p><img src="http://zhuuu-bucket.oss-cn-beijing.aliyuncs.com/img/20201106/160524576.png" alt="mark"></p>
<p>一般来说，在我们接收数据时将数据解码后，就进行业务的相关处理，所以上图的<strong>入站的常用类更多(服务端到客户端)</strong>。<strong>在数据出站时（客户端到服务端）</strong>，一般我们只需要将数据编码后直接发出。</p>
<h2 id="1-Handler-链式调用"><a href="#1-Handler-链式调用" class="headerlink" title="1. Handler 链式调用"></a>1. Handler 链式调用</h2><ul>
<li><p><code>Pipeline</code>中的<code>Handler</code>可以当作一个双向链表。</p>
</li>
<li><p>但是<code>Handler</code>却又存在着入站和出站之分。那么<code>Netty</code>是如何将两种类型的<code>Handler</code>保存在一个链表中，却又能够入站的时候调用<code>InboundHandler</code>，出栈的时候调用<code>OutBoundHandler</code>呢</p>
</li>
<li><p>看下图，黄色的表示入站，以及入站的<code>Handler</code>，绿色的表示出站，以及出站的<code>Handler</code>。</p>
</li>
</ul>
<p><img src="http://zhuuu-bucket.oss-cn-beijing.aliyuncs.com/img/20201106/162411613.png" alt="mark"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">initChannel</span><span class="params">(SocketChannel ch)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    ChannelPipeline pipeline = ch.pipeline();</span><br><span class="line">    pipeline.addLast(<span class="keyword">new</span> LongToByteEncoder()); <span class="comment">//out</span></span><br><span class="line">    pipeline.addLast(<span class="keyword">new</span> ByteToLongDecoder()); <span class="comment">//in</span></span><br><span class="line">    pipeline.addLast(<span class="keyword">new</span> OutBoundHandler()); <span class="comment">//out</span></span><br><span class="line">    pipeline.addLast(<span class="keyword">new</span> InBoundHandler()); <span class="comment">//in</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><strong>请求处理流程</strong></p>
<ul>
<li>当一个请求来了的时候，首先会将请求发给<code>pipeline</code>中位于链表首部的<code>Handler</code>。</li>
<li>首先由队列第一个handler 进行处理，如果接受类型不匹配，那么跳过，直接转发给下一个handler 进行处理</li>
<li>如果需要返回数据，我们就调用<code>writeAndFlush</code>方法，这个方法可不简单，当他一被调用，就会触发出站请求，然后就由当前所在的<code>handler</code> 节点往回调用</li>
</ul>
<p><strong>通过上面的描述，我们可以总结添加<code>Handler</code>的以下节点总结：</strong></p>
<ul>
<li><strong>调用<code>InboundHandler</code>的顺序和添加的顺序是一致的。</strong></li>
<li><strong>调用<code>OutboundHandler</code>的顺序和添加它的顺序是相反的。</strong></li>
<li><strong>链表的末尾不能有 <code>OutHandler</code>，因为如果最后是 <code>OutHandler</code>的话，当他前面的 <code>Inhandler</code> 处理完数据返回消息调用<code>writeAndflush</code> 方法后，它就直接在前面进行反向调用了。那么就无法调用到这个 <code>OutHandler</code></strong></li>
<li><strong>所以，平常会把 <code>OutHandler</code>写在前面，<code>InHandler</code> 一般放在链表的末尾</strong></li>
<li><strong><code>InHandler</code> 一旦进行了 <code>writeAndFlush</code> ，那么只有这个<code>Inhandler</code> 之前添加的 <code>Outhandler</code> 才能正确的处理数据</strong></li>
</ul>
<h2 id="2-Handler-编解码器"><a href="#2-Handler-编解码器" class="headerlink" title="2. Handler 编解码器"></a>2. Handler 编解码器</h2><ul>
<li><p>当<code>Netty</code>发送或者接受一个消息的时候，就将会发生一次数据转换。入站消息会被解码：从字节转换为另一种格式（比如<code>java</code>对象）；如果是出站消息，它会被编码成字节。</p>
</li>
<li><p>Netty提供一系列<strong>实用的编解码器</strong>，他们都实现了<code>ChannelInboundHadnler</code>或者<code>ChannelOutboundHandler</code>接口。在这些类中，<code>channelRead</code>方法已经被重写了</p>
</li>
<li><p><strong>以入站为例</strong>，对于每个从入站<code>Channel</code>读取的消息，这个方法会被调用。随后，它将调用由解码器所提供的<code>decode()</code>方法进行解码，并将已经解码的字节转发给<code>ChannelPipeline</code>中的下一个<code>ChannelInboundHandler</code>。</p>
</li>
</ul>
<h3 id="2-1-解码器-ByteToMessageDecoder"><a href="#2-1-解码器-ByteToMessageDecoder" class="headerlink" title="2.1 解码器-ByteToMessageDecoder"></a>2.1 解码器-ByteToMessageDecoder</h3><ul>
<li>由于<strong>不可能知道远程节点是否会一次性发送一个完整的信息，tcp有可能出现粘包拆包的问题，这个类会对入站数据进行缓冲，直到它准备好被处理。</strong></li>
</ul>
<p><strong>下面是段示例代码：</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ToIntegerDecoder</span> <span class="keyword">extends</span> <span class="title">ByteToMessageDecoder</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">decode</span><span class="params">(ChannelHandlerContext ctx, ByteBuf in, List&lt;Object&gt; out)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (in.readableBytes() &gt;= <span class="number">4</span>) &#123;</span><br><span class="line">            out.add(in.readInt());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>这个例子中</strong></p>
<ol>
<li>每次入站从<code>ByteBuf</code>中读取4字节，将其解码为一个<code>int</code>，</li>
<li>然后将它添加到下一个<code>List</code>中。当没有更多元素可以被添加到该<code>List</code>中时，它的内容将会被发送给下一个<code>ChannelInboundHandler</code>。</li>
<li><code>int</code>在被添加到<code>List</code>中时，会被自动装箱为<code>Integer</code>。</li>
</ol>
<p>在调用<code>readInt()</code>方法前必须验证所输入的<code>ByteBuf</code>是否具有足够的数据</p>
<p><img src="http://zhuuu-bucket.oss-cn-beijing.aliyuncs.com/img/20201106/163527996.png" alt="mark"></p>
<h3 id="2-2-解码器-ReplayingDecoder"><a href="#2-2-解码器-ReplayingDecoder" class="headerlink" title="2.2 解码器 - ReplayingDecoder"></a>2.2 <strong>解码器 - ReplayingDecoder</strong></h3><ul>
<li><code>public abstract class ReplayingDecoder&lt;S&gt; extends ByteToMessageDecoder{ }</code></li>
<li><code>ReplayingDecoder</code>扩展了<code>ByteToMessageDecoder</code>类，使用这个类，我们不必调用<code>readableBytes()</code>方法。参数S指定了用户状态管理的类型，<strong>其中Void代表不需要状态管理</strong></li>
<li>下面是代码示例：这段代码起到了上面<code>ByteToMessageDecoder</code>一样的作用</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ByteToLongDecoder2</span> <span class="keyword">extends</span> <span class="title">ReplayingDecoder</span>&lt;<span class="title">Void</span>&gt; </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">decode</span><span class="params">(ChannelHandlerContext ctx, ByteBuf in, List&lt;Object&gt; out)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        out.add(in.readLong());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<ul>
<li><code>ReplayingDecoder</code>使用方便，但它也有一些局限性：<ul>
<li><strong>并不是所有的 <code>ByteBuf</code> 操作都被支持</strong>，如果调用了一个不被支持的方法，将会抛出一个 <code>UnsupportedOperationException</code>。</li>
<li><code>ReplayingDecoder</code> 在某些情况下可能稍慢于 <code>ByteToMessageDecoder</code>，例如网络缓慢并且消息格式复杂时，消息会被拆成了多个碎片，速度变慢</li>
</ul>
</li>
</ul>
<p><strong>其他的解码器</strong></p>
<ul>
<li><code>LineBasedFrameDecoder</code>：这个类在Netty内部也有使用，它使用行尾控制字符（\n或者\r\n）作为分隔符来解析数据。</li>
<li><code>DelimiterBasedFrameDecoder</code>：使用自定义的特殊字符作为消息的分隔符。</li>
<li><code>HttpObjectDecoder</code>：一个HTTP数据的解码器</li>
<li><code>LengthFieldBasedFrameDecoder</code>：通过指定长度来标识整包消息，这样就可以自动的处理黏包和半包消息。</li>
</ul>
<h2 id="3-简单实例"><a href="#3-简单实例" class="headerlink" title="3. 简单实例"></a>3. 简单实例</h2><p><strong>实例要求：</strong></p>
<ul>
<li>使用自定义的编码器和解码器来说明Netty的<code>handler</code> 调用机制</li>
<li>客户端发送<code>long</code> -&gt; 服务器</li>
<li>服务端发送<code>long</code>-&gt; 客户端</li>
</ul>
<p><img src="http://zhuuu-bucket.oss-cn-beijing.aliyuncs.com/img/20201106/172833866.png" alt="mark"></p>
<p>注意 ：  这里只展示，<code>Handler</code>相应的代码和添加<code>Handler</code>的关键代码。</p>
<ol>
<li><strong>Decoder</strong></li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ByteToLongDecoder</span> <span class="keyword">extends</span> <span class="title">ByteToMessageDecoder</span> </span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * decode 方法会根据接收到的数据，被调用多次，知道确定没有新的元素被添加到list，或者是ByteBuf 没有更多的可读字节为止</span></span><br><span class="line"><span class="comment">     * 如果 list out不为空，就会将list的内容传递给下一个 Handler 进行处理，该处理器的方法也会被调用多次。</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> ctx 上下文对象</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> in 入栈的 ByteBuf</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> out list集合，将解码后的数据传给下一个Handler</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> Exception</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">decode</span><span class="params">(ChannelHandlerContext ctx, ByteBuf in, List&lt;Object&gt; out)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">//因为long为8个字节，所以需要8个字节才能读取成一个long类型的数据</span></span><br><span class="line">        System.out.println(<span class="string">"ByteToLongDecoder：入栈数据被解码"</span>);</span><br><span class="line">        <span class="keyword">if</span> (in.readableBytes() &gt;= <span class="number">8</span>)&#123;</span><br><span class="line">            out.add(in.readLong());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<ol start="2">
<li><strong>Encoder</strong></li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LongToByteEncoder</span> <span class="keyword">extends</span> <span class="title">MessageToByteEncoder</span>&lt;<span class="title">Long</span>&gt; </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">encode</span><span class="params">(ChannelHandlerContext ctx, Long msg, ByteBuf out)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"LongToByteEncoder: 出栈数据，msg = "</span> + msg);</span><br><span class="line">        out.writeLong(msg);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<ol start="3">
<li><strong>服务器端添加Handler</strong></li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">initChannel</span><span class="params">(SocketChannel ch)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    ChannelPipeline pipeline = ch.pipeline();</span><br><span class="line">    pipeline.addLast(<span class="keyword">new</span> LongToByteEncoder()); <span class="comment">//编码器，出站</span></span><br><span class="line">    pipeline.addLast(<span class="keyword">new</span> ByteToLongDecoder()); <span class="comment">//解码器，入站</span></span><br><span class="line">    pipeline.addLast(<span class="keyword">new</span> ServerInBoundHandler()); <span class="comment">//业务处理，入站</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<ol start="4">
<li><strong>客户端添加Handler</strong></li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">initChannel</span><span class="params">(SocketChannel ch)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    ChannelPipeline pipeline = ch.pipeline();</span><br><span class="line">    pipeline.addLast(<span class="keyword">new</span> LongToByteEncoder()); <span class="comment">//编码器，出站</span></span><br><span class="line">    pipeline.addLast(<span class="keyword">new</span> ByteToLongDecoder()); <span class="comment">//解码器，入站</span></span><br><span class="line">    pipeline.addLast(<span class="keyword">new</span> ClientInBoundHandler()); <span class="comment">//业务处理，入站。</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><strong>注意：</strong></p>
<ul>
<li>这里当客户端和服务端接收消息的时候<ul>
<li>首先会调用入站的解码器，然后进行业务的处理</li>
<li>然后在调用出站的解码解码器再返回消息</li>
</ul>
</li>
<li>后面可以在业务处理类中，增加发送消息的代码，此处省略。</li>
</ul>
<h2 id="4-Netty整合-log4j"><a href="#4-Netty整合-log4j" class="headerlink" title="4. Netty整合 log4j"></a>4. Netty整合 log4j</h2><ol>
<li><strong>添加依赖</strong></li>
</ol>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;log4j&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;log4j&lt;/artifactId&gt;</span><br><span class="line">    &lt;version&gt;1.2.17&lt;/version&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.slf4j&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt;</span><br><span class="line">    &lt;version&gt;1.7.25&lt;/version&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.slf4j&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;slf4j-log4j12&lt;/artifactId&gt;</span><br><span class="line">    &lt;version&gt;1.7.25&lt;/version&gt;</span><br><span class="line">    &lt;scope&gt;test&lt;/scope&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.slf4j&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;slf4j-simple&lt;/artifactId&gt;</span><br><span class="line">    &lt;version&gt;1.7.25&lt;/version&gt;</span><br><span class="line">    &lt;scope&gt;test&lt;/scope&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>



<ol start="2">
<li><strong>添加配置文件</strong></li>
</ol>
<p>在<code>resource</code>目录下新建<code>log4j.properties</code>即可</p>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">log5j.rootLogger</span>=<span class="string">DEBUG, stdout</span></span><br><span class="line"><span class="meta">log4j.appender.stdout</span>=<span class="string">org.apache.log4j.ConsoleAppender</span></span><br><span class="line"><span class="meta">log4j.appender.stdout.layout</span>=<span class="string">org.apache.log4j.PatternLayout</span></span><br><span class="line"><span class="meta">log4j.appender.stdout.layout.ConversionPattern</span>=<span class="string">[%p] %C&#123;1&#125; - %m%n</span></span><br></pre></td></tr></table></figure>







<blockquote>
<p> 本文档整理自 尚硅谷韩顺平Netty 相关课程。</p>
</blockquote>
<p><strong>参考博客 ：</strong> <a href="https://dongzl.github.io/netty-handbook/#/README" target="_blank" rel="noopener">https://dongzl.github.io/netty-handbook/#/README</a></p>

      
      <!-- reward -->
      
      <div id="reward-btn">
        打赏
      </div>
      
    </div>
      <!-- copyright -->
      
        <div class="declare">
          <ul class="post-copyright">
            <li>
              <i class="ri-copyright-line"></i>
              <strong>版权声明： </strong s>
              本博客所有文章除特别声明外，均采用 <a href="https://www.apache.org/licenses/LICENSE-2.0.html" rel="external nofollow"
                target="_blank">Apache License 2.0</a> 许可协议。转载请注明出处！
            </li>
          </ul>
        </div>
        
    <footer class="article-footer">
      
          
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://zhuuu.work/2020/11/05/Netty/Netty-12-handler%E8%B0%83%E7%94%A8%E6%9C%BA%E5%88%B6/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Netty/" rel="tag">Netty</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/handler/" rel="tag">handler</a></li></ul>


    </footer>

  </div>

  
  
  <nav class="article-nav">
    
      <a href="/2020/11/05/Leetcode/Leetcode-127-%E5%8D%95%E8%AF%8D%E6%8E%A5%E9%BE%99/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            Leetcode-127-单词接龙
          
        </div>
      </a>
    
    
      <a href="/2020/11/04/Leetcode/Leetcode-057-%E6%8F%92%E5%85%A5%E5%8C%BA%E9%97%B4/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">Leetcode-057-插入区间</div>
      </a>
    
  </nav>


  

  
  
<!-- valine评论 -->
<div id="vcomments-box">
    <div id="vcomments">
    </div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src='https://cdn.jsdelivr.net/npm/valine@1.3.10/dist/Valine.min.js'></script>
<script>
    new Valine({
        el: '#vcomments',
        notify: false,
        verify: '',
        app_id: '',
        app_key: '',
        path: window.location.pathname,
        avatar: 'mp',
        placeholder: '给我的文章加点评论吧~',
        recordIP: true
    });
    const infoEle = document.querySelector('#vcomments .info');
    if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
        infoEle.childNodes.forEach(function (item) {
            item.parentNode.removeChild(item);
        });
    }
</script>
<style>
    #vcomments-box {
        padding: 5px 30px;
    }

    @media screen and (max-width: 800px) {
        #vcomments-box {
            padding: 5px 0px;
        }
    }

    #vcomments-box #vcomments {
        background-color: #fff;
    }

    .v .vlist .vcard .vh {
        padding-right: 20px;
    }

    .v .vlist .vcard {
        padding-left: 10px;
    }
</style>

  

  
  
<div class="gitalk" id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1.5.0/dist/gitalk.css">


<script src="https://cdn.jsdelivr.net/npm/gitalk@1.5.0/dist/gitalk.min.js"></script>


<script src="https://cdn.jsdelivr.net/npm/blueimp-md5@2.10.0/js/md5.min.js"></script>

<script type="text/javascript">
  var gitalk = new Gitalk({
    clientID: 'db188ed8c86dc4b0dbf3',
    clientSecret: 'a58f92160e5a9efd726b7d533000a0737f3e3f3e',
    repo: 'Blog-comments',
    owner: 'Zhuuuuuuuu',
    admin: ['Zhuuuuuuuu'],
    // id: location.pathname,      // Ensure uniqueness and length less than 50
    id: md5(location.pathname),
    distractionFreeMode: false,  // Facebook-like distraction free mode
    pagerDirection: 'last'
  })

  gitalk.render('gitalk-container')
</script>

  

</article>
</section>
      <footer class="footer">
  <div class="outer">
    <ul class="list-inline">
      <li>
        &copy;
        2019-2021
        Zhuuu
      </li>
      <li>
        
      </li>
    </ul>
    <ul class="list-inline">
      <li>
        
        
        <span>
  <i>PV:<span id="busuanzi_value_page_pv"></span></i>
  <i>UV:<span id="busuanzi_value_site_uv"></span></i>
</span>
        
      </li>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>
    <div class="to_top">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>
      </div>
    </main>
      <aside class="sidebar">
        <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="朱酱酱的学习博客"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/JVM/">JVM</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/JDK%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/">JDK源码</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/">多线程</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/Mysql/">Mysql</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/Redis/">Redis</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/%E8%AE%BE%E8%AE%A1%E8%80%85%E6%A8%A1%E5%BC%8F/">设计模式</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/MyBatis/">MyBatis</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/SpringMVC/">SpringMVC</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/Spring/">Spring</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/SpringBoot/">SpringBoot</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">Linux</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/Leetcode/">Leetcode</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/%E5%89%8D%E7%AB%AF/">前端</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/">网络编程</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/photoshop/">photoshop</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="http://smartzhuuu.lofter.com/" target="_blank" rel="noopener">摄影</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/2020/about">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
      </aside>
      <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="/images/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="/images/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
      
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/jquery.justifiedGallery.min.js"></script>


<script src="/js/lazyload.min.js"></script>


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<script src="/js/share.js"></script>



<script src="/fancybox/jquery.fancybox.min.js"></script>




<script>
  try {
    var typed = new Typed("#subtitle", {
    strings: ['昨夜西风凋碧树。独上高楼，望尽天涯路','衣带渐宽终不悔，为伊消得人憔悴。','众里寻他千百度。蓦然回首，那人却在，灯火阑珊处。'],
    startDelay: 0,
    typeSpeed: 200,
    loop: true,
    backSpeed: 100,
    showCursor: true
    });
  } catch (err) {
  }
  
</script>




<script src="/js/tocbot.min.js"></script>

<script>
  // Tocbot_v4.7.0  http://tscanlin.github.io/tocbot/
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer:'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto',
    onClick: (e) => {
      $('.toc-link').removeClass('is-active-link');
      $(`a[href=${e.target.hash}]`).addClass('is-active-link');
      $(e.target.hash).scrollIntoView();
      return false;
    }
  });
</script>


<script>
  var ayerConfig = {
    mathjax: true
  }
</script>


<script src="/js/ayer.js"></script>


<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>



<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
      tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
  });

  MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
      for(i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
      }
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@2.7.6/unpacked/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>


<script type="text/javascript" src="https://js.users.51.la/20544303.js"></script>
  </div>
</body>

</html>